<template>
  <div>
    <el-form label-position="top">
      <el-form-item label="搜索类型">
        <el-select v-model="selectedType" remote filterable :remote-method="searchType">
          <el-option v-for="type in types.list" :value="type.id" :key="type.id" :label="type.name"/>
        </el-select>
        <el-button type="success" size="small" @click="createType">创建类型</el-button>
      </el-form-item>
      <template v-if="types.selected !== null">
        <el-form-item label="与以下平台绑定关系（绑定后无法取消关系）">
          <el-checkbox-group v-model="platforms.selected" @change="savePTA">
            <el-checkbox v-for="p in platforms.list" :key="p.id" :label="p.id"
                         :disabled="platforms.selected.includes(p.id)">{{p.name}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
  import _ from 'lodash';

  export default {
    name: 'typeManager',
    data() {
      return {
        platforms: {selected: [], list: []},
        type: {name: ''},
        types: {selected: null, list: {}},

      };
    },
    methods: {
      async loadPlatforms() {
        const res = await this.$http.get('/api/types/platforms');
        this.platforms.list = res.data;
      },
      async searchType(query) {
        const res = await this.$http.get('/api/types/search?search=' + query);
        this.types.list = _.keyBy(res.data, 'id');
        this.type = {name: query};
        this.types.selected = null;
      },
      async createType() {
        const res = await this.$http.post('/api/types', this.type);
        this.types.list[res.data.id] = res.data;
        this.types.selected = res.data.id;
        this.loadPlatformTypeAssociation();
      },
      async loadPlatformTypeAssociation() {
        const res = await this.$http.get('/api/types/' + this.types.selected);
        this.platforms.selected = res.data;
      },
      savePTA() {
        console.log('savePTA', this.types.selected);
        if (!this.types.selected)
          return;
        this.platforms.selected.forEach(platform_id => {
          this.$http.get('/api/types/bind/' + platform_id + '/' + this.types.selected);
        });
      },
    },
    computed: {
      selectedType: {
        set(type_id) {
          this.types.selected = type_id;
          this.loadPlatformTypeAssociation();
        },
        get() {
          return this.types.selected;
        },
      },
    },
    mounted() {
      this.loadPlatforms();
    },
  };
</script>

<style scoped>

</style>